// addrspace.cc 
//	Routines to manage address spaces (executing user programs).
//
//	In order to run a user program, you must:
//
//	1. link with the -N -T 0 option 
//	2. run coff2noff to convert the object file to Nachos format
//		(Nachos object code format is essentially just a simpler
//		version of the UNIX executable object code format)
//	3. load the NOFF file into the Nachos file system
//		(if you haven't implemented the file system yet, you
//		don't need to do this last step)
//
// Copyright (c) 1992-1993 The Regents of the University of California.
// All rights reserved.  See copyright.h for copyright notice and limitation 
// of liability and disclaimer of warranty provisions.

#include "copyright.h"
#include "system.h"
#include "addrspace.h"
#include "noff.h"
#include "table.h"
#include "synch.h"

#ifdef CHANGED
#include "bitmap.h"

#endif

extern "C" { int bzero(char *, int); };

Table::Table(int s) : map(s), table(0), lock(0), size(s) {
    table = new void *[size];
    lock = new Lock("TableLock");
}

Table::~Table() {
    if (table) {
	delete table;
	table = 0;
    }
    if (lock) {
	delete lock;
	lock = 0;
    }
}

void *Table::Get(int i) {
    // Return the element associated with the given if, or 0 if
    // there is none.

    return (i >=0 && i < size && map.Test(i)) ? table[i] : 0;
}

int Table::Put(void *f) {
    // Put the element in the table and return the slot it used.  Use a
    // lock so 2 files don't get the same space.
    int i;	// to find the next slot

    lock->Acquire();
    i = map.Find();
    lock->Release();
    if ( i != -1)
	table[i] = f;
    return i;
}

void *Table::Remove(int i) {
    // Remove the element associated with identifier i from the table,
    // and return it.

    void *f =0;

    if ( i >= 0 && i < size ) {
	lock->Acquire();
	if ( map.Test(i) ) {
	    map.Clear(i);
	    f = table[i];
	    table[i] = 0;
	}
	lock->Release();
    }
    return f;
}

//----------------------------------------------------------------------
// SwapHeader
// 	Do little endian to big endian conversion on the bytes in the 
//	object file header, in case the file was generated on a little
//	endian machine, and we're now running on a big endian machine.
//----------------------------------------------------------------------

static void 
SwapHeader (NoffHeader *noffH)
{
	noffH->noffMagic = WordToHost(noffH->noffMagic);
	noffH->code.size = WordToHost(noffH->code.size);
	noffH->code.virtualAddr = WordToHost(noffH->code.virtualAddr);
	noffH->code.inFileAddr = WordToHost(noffH->code.inFileAddr);
	noffH->initData.size = WordToHost(noffH->initData.size);
	noffH->initData.virtualAddr = WordToHost(noffH->initData.virtualAddr);
	noffH->initData.inFileAddr = WordToHost(noffH->initData.inFileAddr);
	noffH->uninitData.size = WordToHost(noffH->uninitData.size);
	noffH->uninitData.virtualAddr = WordToHost(noffH->uninitData.virtualAddr);
	noffH->uninitData.inFileAddr = WordToHost(noffH->uninitData.inFileAddr);
}

//----------------------------------------------------------------------
// AddrSpace::AddrSpace
// 	Create an address space to run a user program.
//	Load the program from a file "executable", and set everything
//	up so that we can start executing user instructions.
//
//	Assumes that the object code file is in NOFF format.
//
//	"executable" is the file containing the object code to load into memory
//
//      It's possible to fail to fully construct the address space for
//      several reasons, including being unable to allocate memory,
//      and being unable to read key parts of the executable.
//      Incompletely consretucted address spaces have the member
//      constructed set to false.
//----------------------------------------------------------------------

AddrSpace::AddrSpace(OpenFile *executable) : fileTable(MaxOpenFiles) {
	NoffHeader noffH;
    unsigned  x, size, numStackPages;
	memoryAccessLock = new Lock ("Memory Access Lock");
	memoryAccessLock->Acquire();
    // Don't allocate the input or output to disk files
    fileTable.Put(0);
    fileTable.Put(0);

    executable->ReadAt((char *)&noffH, sizeof(noffH), 0);
    if ((noffH.noffMagic != NOFFMAGIC) && 
		(WordToHost(noffH.noffMagic) == NOFFMAGIC))
    	SwapHeader(&noffH);
    ASSERT(noffH.noffMagic == NOFFMAGIC);

	exec = executable;

    size = noffH.code.size + noffH.initData.size + noffH.uninitData.size ;
	numPages =  divRoundUp(size, PageSize) + divRoundUp(UserStackSize,PageSize);
	numStackPages = divRoundUp(UserStackSize,PageSize);//calculate numStackPages separately to use later to zero out that section of 
	codeStart=noffH.code.inFileAddr;
                                                
    size = numPages * PageSize;
	maxSize = numPages+(MAX_NUMBER_OF_THREADS-1)*numStackPages;

    DEBUG('a', "Initializing address space, num pages %d, size %d\n", 
					numPages, size);

#ifdef CHANGED
	 // Prevent context switches that would involve another process/thread allocating memory
								 // that is found usable here
	execLocation = new int[noffH.code.size + noffH.initData.size];
	swapFileLoc = new int[maxSize]; //number of possible entries for this address space
	location = new int[maxSize]; //(0=main memory; 1=executable; 2=swap file; 3=?)
	pageTable = new TranslationEntry[maxSize];//initialize page table to hold all possible stack that might be assigned
   for(int i = 0; i< maxSize; i++)
	{
		location[i]=1;
		swapFileLoc[i]=-1;
		if (i<noffH.code.size)
			execLocation[i]=noffH.code.inFileAddr + (i*PageSize);
		else if ((i-noffH.code.size)<noffH.initData.size)
			execLocation[i]= noffH.initData.inFileAddr + (i*PageSize);
		else
			location[i]=3;
	}

	memoryAccessLock->Release();
#endif

}
#ifdef CHANGED
int AddrSpace::AllocateStack()
{
	unsigned int numStackPages;
	memoryAccessLock->Acquire(); // Prevent context switches that would involve another process/thread allocating memory
								 // that is found usable here
	numStackPages = divRoundUp(UserStackSize,PageSize);
	for (unsigned int i = 0; i < numStackPages; i++, numPages++)
	{
		location[numPages] = 3;
	}
	//machine->pageTable = pageTable;
	machine->pageTableSize = numPages;
	memoryAccessLock->Release();
	return (numPages);// needs to be number for the beginning of stack not the end
}

void AddrSpace::DeallocateStack(int virtualAddressThread, int virtualAddressProcess)
{
	memoryAccessLock->Acquire();
	int numStackPages = divRoundUp(UserStackSize,PageSize);
	
	for (unsigned int i = 0; i < numStackPages; i++, numPages++)
	{
		
	}
	memoryAccessLock->Release();
}

void AddrSpace::LoadFromExec(int vpn, int ppn)
{
	exec->ReadAt(&(machine->mainMemory[ppn*PageSize]), //Reading a page at time from the start of the file
			PageSize, execLocation[vpn]);	
	location[vpn]=0;
}

void AddrSpace::FreeSwap()
{
	for (int i = 0; i<maxSize; i++)
	{
		if (swapFileLoc[i]!=-1)
			swapFileCheck->Clear(swapFileLoc[i]);
	}
}

void AddrSpace::LoadFromSwap(int vpn, int ppn)
{
	//swapAccessLock->Acquire();
	swapFile->ReadAt(&(machine->mainMemory[ppn*PageSize]), PageSize, swapFileLoc[vpn]*PageSize);
	location[vpn]=0;
	//swapAccessLock->Release();
}

void AddrSpace::MovedToSwap(int vpn, int swapLoc)
{
	location[vpn] = 2; // 2= swap file
	swapFileLoc[vpn] = swapLoc;
}

void AddrSpace::Evict(int vpn)
{
	if(swapFileLoc[vpn]!=-1) //ie there is a good copy in swap
		location[vpn]=2; //set location to swap
	else //no copy in swap so must never have been modified
	{
		if(location[vpn]!=3)
			location[vpn]=1; //set location to executable
		else
			location[vpn]=3;
	}
}

void AddrSpace::InitializeStack(int vpn)
{

	location[vpn] = 0;

}

#endif
//----------------------------------------------------------------------
// AddrSpace::~AddrSpace
//
// 	Dealloate an address space.  release pages, page tables, files
// 	and file tables
//----------------------------------------------------------------------

AddrSpace::~AddrSpace()
{
    delete pageTable;
	//delete exec;
	delete location;
	delete swapFileLoc;
	delete execLocation;
}

//----------------------------------------------------------------------
// AddrSpace::InitRegisters
// 	Set the initial values for the user-level register set.
//
// 	We write these directly into the "machine" registers, so
//	that we can immediately jump to user code.  Note that these
//	will be saved/restored into the currentThread->userRegisters
//	when this thread is context switched out.
//----------------------------------------------------------------------

void
AddrSpace::InitRegisters()
{
    int i;
    for (i = 0; i < NumTotalRegs; i++)
	machine->WriteRegister(i, 0);

    // Initial program counter -- must be location of "Start"
    machine->WriteRegister(PCReg, 0);	

    // Need to also tell MIPS where next instruction is, because
    // of branch delay possibility
    machine->WriteRegister(NextPCReg, 4);

   // Set the stack register to the end of the address space, where we
   // allocated the stack; but subtract off a bit, to make sure we don't
   // accidentally reference off the end!
    machine->WriteRegister(StackReg, (numPages) * PageSize - 16);
    DEBUG('a', "Initializing stack register to %x\n", (numPages-1) * PageSize - 16);	
}

//----------------------------------------------------------------------
// AddrSpace::SaveState
// 	On a context switch, save any machine state, specific
//	to this address space, that needs saving.
//
//	For now, nothing!
//----------------------------------------------------------------------

void AddrSpace::SaveState() 
{
#ifdef CHANGED
	//pageTable = machine->pageTable;
	for (int i = 0; i<TLBSize; i++)
	{
		if(machine->tlb[i].valid && machine->tlb[i].dirty)
			ipt->MakeDirty(machine->tlb[i].physicalPage);
		machine->tlb[i].valid = FALSE;
	}
    numPages = machine->pageTableSize;
#endif
}

//----------------------------------------------------------------------
// AddrSpace::RestoreState
// 	On a context switch, restore the machine state so that
//	this address space can run.
//
//      For now, tell the machine where to find the page table.
//----------------------------------------------------------------------

void AddrSpace::RestoreState() 
{
#ifdef CHANGED  
	//machine->pageTable = pageTable;
	for (int i = 0; i<TLBSize; i++)
	{
		if(machine->tlb[i].valid && machine->tlb[i].dirty)
			ipt->MakeDirty(machine->tlb[i].physicalPage);
		machine->tlb[i].valid = FALSE;
	}
		
    machine->pageTableSize = numPages;
#endif
}
